package com.thx.role.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.thx.common.orm.PaginationDao;
import com.thx.common.util.AppContext;
import com.thx.role.model.Role;

@Repository
public class RoleDao extends PaginationDao<Role> {

	public Role findByRoleName(String roleName) {
		String hql = "from Role where comId = ? and roleName = ? and status = '1'";
		List<Role> roles = createQuery(hql, AppContext.getCurrentComId(), StringUtils.strip(roleName)).list();
		if (roles != null && roles.size() > 0)
			return roles.get(0);
		return null;
	}

	public List<Role> searchRole(String roleName) {
		String hql = "from Role where comId = ? and status='1'";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(roleName)) {
			hql += " and roleName like ?";
			objs.add("%"+StringUtils.strip(roleName)+"%");
		}
		hql += " order by createDate desc";
		return findPageList(hql, objs.toArray());
	}

	public List<Role> searchAllRoles(String roleName) {
		String hql = "from Role where comId = ? and status = '1'";
		List<Object> objs =new ArrayList<Object>();
		objs.add(AppContext.getCurrentComId());
		if (StringUtils.isNotBlank(roleName)) {
			hql += " and roleName like ?";
			objs.add("%"+StringUtils.strip(roleName)+"%");
		}
		hql += " order by createDate desc";
		return createQuery(hql, objs.toArray()).list();
	}

	public List<Role> findByUserId(String userId) {
		if (StringUtils.isNotBlank(userId)) {
			String sql = "select r.* from org_role r LEFT JOIN org_user_roles ur ON r.ROLE_ID=ur.roles WHERE ur.users=?";
			return createSqlQuery(sql, StringUtils.strip(userId)).addEntity(Role.class).list();
		}
		return null;
	}

}
